<template>
  <div class="px-20 pt-4 pb-10">
    <div class="text-center text-lg font-bold mb-4">一日一赋系统【首页看板】</div>
    <el-row :gutter="20">
      <!-- 当月业绩目标 -->
      <el-col :span="8" style="padding-left: 10px">
        <el-card>
          <template #header>
            <div class="flex items-center">
              <h3>当月业绩目标</h3>
              <!--              <div class="ml-2">(进度{{ personTargetCompletionRate }}%)</div>-->
            </div>
          </template>
          <div class="flex justify-center items-center" style="height: 430px">
            <div class="font-bold text-4xl text-red">{{ personTargetCompletionRate }} %</div>
          </div>
          <!--          <div class="text-center">{{ personTargetCompletionRateStr }}</div>-->
          <!--          <div ref="monthTargetRef" style="height: 420px" />-->
        </el-card>
      </el-col>
      <!-- 当月任务进度 -->
      <el-col :span="8" style="padding-left: 10px">
        <el-card>
          <template #header>
            <div class="flex items-center">
              <h3>当月任务进度</h3>
              <!--              <div class="ml-2">(进度{{ taskCompletionRate }}%)</div>-->
            </div>
          </template>
          <div class="flex justify-center items-center" style="height: 430px">
            <!--            <div class="font-bold text-4xl text-red">{{ taskCompletionRate }} %</div>-->
            <div class="font-bold text-4xl text-red">{{ taskOverQuantity }} - {{ taskTotalQuantity }}</div>
          </div>
          <!--          <div class="text-center">{{ taskCompletionRateStr }}</div>-->
          <!--          <div ref="taskRef" style="height: 420px" />-->
        </el-card>
      </el-col>
      <!-- 未处理通知 -->
      <el-col :span="8" style="padding-left: 10px">
        <el-card>
          <template #header>
            <div class="flex items-center">
              <h3>未处理通知</h3>
              <div class="ml-2">({{ userMessageTotal }}条)</div>
            </div>
          </template>
          <div class="flex justify-center items-center" style="height: 430px">
            <div class="font-bold text-4xl text-red">{{ userMessageTotal }}条通知</div>
          </div>
        </el-card>
      </el-col>
      <!-- 当月任务列表 -->
      <el-col :span="12" class="mt-4">
        <el-card>
          <template #header>
            <h3>当月任务列表</h3>
          </template>
          <el-table :data="taskList" style="width: 100%">
            <el-table-column prop="name" label="任务名称" width="180">
              <template #default="scope">
                {{ scope.row.taskName }}
              </template>
            </el-table-column>
            <el-table-column prop="expectedStartTime" label="预计开始时间" width="180" />
            <el-table-column prop="expectedEndTime" label="预计完成时间" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                {{ task_status.find((item) => item.value == scope.row.status)?.label }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12" class="mt-4">
        <el-card>
          <template #header>
            <h3>今日待处理通知</h3>
          </template>
          <el-table :data="userMessageList" style="width: 100%">
            <el-table-column prop="name" label="消息名称" width="650px">
              <template #default="scope">
                {{ scope.row.messageTitle }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- <TaskEdit ref="taskEditForm" v-model:task-id="taskId" v-model:visible="taskEditVisible"></TaskEdit> -->
    <el-dialog v-model:visible="dialog.visible" title="员工未完成任务列表" append-to-body>
      <!--      <div v-for="info in employeeTaskInfo" :key="info.employeeName">-->
      <!--        <p>{{ info.employeeName }}</p>-->
      <!--        <p>历史逾期任务:</p>-->
      <!--        <ul>-->
      <!--          <li v-for="taskName in info.historyExceedTaskList" :key="taskName">{{ taskName }}</li>-->
      <!--        </ul>-->
      <!--        <p>今日未完成任务:</p>-->
      <!--        <ul>-->
      <!--          <li v-for="taskName in info.todayUnFinishedTaskList" :key="taskName">{{ taskName }}</li>-->
      <!--        </ul>-->
      <!--        <p>未审核通过的任务:</p>-->
      <!--        <ul>-->
      <!--          <li v-for="taskName in info.unauditedTaskList" :key="taskName">{{ taskName }}</li>-->
      <!--        </ul>-->
      <!--        <p>待我审批的任务:</p>-->
      <!--        <ul>-->
      <!--          <li v-for="taskName in info.waitingForMyApprovalTaskList" :key="taskName">{{ taskName }}</li>-->
      <!--        </ul>-->
      <!--      </div>-->
      <el-button @click="dialog.visible = false">关闭</el-button>
    </el-dialog>
  </div>
</template>

<script setup name="Index" lang="ts">
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { task_status } = toRefs<any>(proxy?.useDict('task_status'));

import * as echarts from 'echarts';
import { statPersonTargetCompletion, statTaskCompletion, selectTaskList, selectUserMessage, getEmployeeTaskProgress } from '@/api/stat/stat';
import { TaskVO } from '@/api/task/task/types';
import { UserMessageVO } from '@/api/userMessage/userMessage/types';
import EmployeeTaskProgress from '@/views/popup/EmployeeTaskProgress.vue';
// import { initSSE } from '@/utils/sse';

// const { dialogVisible, employeeTaskInfo } = initSSE('/oa/popup/api/task-progress-sse');

// import TaskEdit from '@/views/task/TaskEdit.vue';

import axios from 'axios';

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// const employeeTaskInfo = ref([]);

const taskId = ref(0);
const taskEditVisible = ref(false);

const personTargetCompletionRate = ref(0.0);
const personTargetCompletionRateStr = ref();

const taskCompletionRate = ref(0.0);
const taskCompletionRateStr = ref();
const taskOverQuantity = ref(0);
const taskTotalQuantity = ref(0);
// 月度 业绩目标完成度 饼状图 引用
// const monthTargetRef = ref();
// 月度 任务完成度 饼状图 引用
// const taskRef = ref();
// 当月任务列表
const taskList = ref<TaskVO[]>([]);
// 编辑任务对象
// const taskEditForm = ref(null);

const userMessageTotal = ref(0);

const userMessageList = ref<UserMessageVO[]>([]);

const init = async () => {
  // 发异步请求获取数据
  let res = await statPersonTargetCompletion();
  // debugger;
  // 设置 业绩目标完成度
  let personTargetCompletionVo = res.data;
  personTargetCompletionRate.value = personTargetCompletionVo.completionRate * 100;
  personTargetCompletionRateStr.value = personTargetCompletionVo.completedValue + '/' + personTargetCompletionVo.targetValue;
  // 业绩目标饼图
  // const monthTargetIntance = echarts.init(monthTargetRef.value, 'macarons');
  // monthTargetIntance.setOption({
  //   tooltip: {
  //     trigger: 'item',
  //     formatter: '{a} <br/>{b} : {c} ({d}%)'
  //   },
  //   series: [
  //     {
  //       name: '当月业绩目标',
  //       type: 'pie',
  //       data: [
  //         { name: '未完成', value: personTargetCompletionVo.targetValue - personTargetCompletionVo.completedValue },
  //         { name: '已完成', value: personTargetCompletionVo.completedValue }
  //       ],
  //       animationEasing: 'cubicInOut',
  //       animationDuration: 1000
  //     }
  //   ]
  // });
  // 设置 任务完成度
  let taskCompletionResult = await statTaskCompletion();
  let taskCompletionRateVo = taskCompletionResult.data;

  taskCompletionRate.value = taskCompletionRateVo.taskCompletionRate * 100;
  taskCompletionRateStr.value = taskCompletionRateVo.overQuantity + '/' + taskCompletionRateVo.totalQuantity;

  taskOverQuantity.value = taskCompletionRateVo.overQuantity;
  taskTotalQuantity.value = taskCompletionRateVo.totalQuantity;
  // 任务饼图
  // const taskIntance = echarts.init(taskRef.value, 'macarons');
  // taskIntance.setOption({
  //   tooltip: {
  //     trigger: 'item',
  //     formatter: '{a} <br/>{b} : {c} ({d}%)'
  //   },
  //   series: [
  //     {
  //       name: '当月任务进度',
  //       type: 'pie',
  //       data: [
  //         { name: '未开始', value: taskCompletionRateVo.initQuantity },
  //         { name: '进行中', value: taskCompletionRateVo.runningQuantity },
  //         { name: '已完成', value: taskCompletionRateVo.finishedQuantity },
  //         { name: '已驳回', value: taskCompletionRateVo.rejectQuantity },
  //         { name: '已结束', value: taskCompletionRateVo.overQuantity },
  //         { name: '已逾期', value: taskCompletionRateVo.exceedQuantity }
  //       ],
  //       animationEasing: 'cubicInOut',
  //       animationDuration: 1000
  //     }
  //   ]
  // });

  // window.addEventListener('resize', () => {
  //   monthTargetIntance.resize();
  //   taskIntance.resize();
  // });

  // 当月任务列表
  let taskResult = await selectTaskList();
  taskList.value = taskResult.data;

  let userMessageResult = await selectUserMessage();
  userMessageTotal.value = userMessageResult.data.length;
  userMessageList.value = userMessageResult.data;
};

const setTimer = () => {
  const now = new Date();
  const targetTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 17, 0, 0);

  if (now > targetTime) {
    // 如果当前时间已经超过下午五点，则设置为明天下午五点
    targetTime.setDate(targetTime.getDate() + 1);
  }

  const delay = targetTime.getTime() - now.getTime();

  setTimeout(() => {
    getTaskProgress();
    // 每天重复执行
    setInterval(getTaskProgress, 24 * 60 * 60 * 1000);
  }, delay);
};

const getTaskProgress = async () => {
  try {
    await nextTick();
    // const response = await getEmployeeTaskProgress();
    // employeeTaskInfo.value = response.data;
    dialog.visible = true;
  } catch (error) {
    console.error('获取任务进度数据失败:', error);
  }
};

// const editTask = (tempTaskId) => {
//   taskId.value = tempTaskId;
//   taskEditVisible.value = true;
// };

watch(dialog, async (newValue) => {
  if (newValue) {
    await nextTick();
    // 在这里执行需要在对话框加载出来后进行的操作
    console.log('对话框已加载出来');
    // 例如获取对话框中的元素
    const dialogElement = document.querySelector('.el-dialog');
    if (dialogElement) {
      console.log('对话框元素:', dialogElement);
    }
  }
});

onMounted(() => {
  init();

  // setTimer();
  getTaskProgress();
});
</script>

<style lang="scss">
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}
</style>
